<template>
  <el-dialog
      :title="templateInfo.name + '（绑定参数）'"
      :visible.sync="showDialog"
      :close-on-click-modal="false"
      top="2vh"
      width="70%"
      @close="closeDialog"
  >
    <div style="width: 100%;height: 72vh;overflow:hidden auto;">
      <TemplateParams v-if="showDialog" ref="TemplateParams"/>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取 消</el-button>
      <el-button type="warning" :loading="btnLoading" @click="submitForm(true)">
        清空参数
      </el-button>
      <el-button type="primary" :loading="btnLoading" @click="submitForm(false)">
        保 存
      </el-button>
    </span>
  </el-dialog>
</template>

<script>

import {cloneDeep} from "lodash-es";
import {saveTemplateParams} from "@/api/tool/genTemplate";
import TemplateParams from "./TemplateParams";

export default {
  name: "BindParams",
  components: {TemplateParams},
  data() {
    return {
      showDialog: false,
      btnLoading: false,
      templateInfo: {}
    }
  },
  methods: {
    // 打开弹窗
    openDialog(template) {
      this.templateInfo = cloneDeep(template)
      this.showDialog = true
      this.$nextTick(() => {
        this.$refs.TemplateParams.initParams(template.paramsList)
      })
    },
    // 关闭弹窗
    closeDialog() {
      this.showDialog = false
      this.$emit('flushData')
    },
    // 保存、清空按钮
    submitForm(isClear) {
      if (isClear) {
        this.$modal.confirm('确定要清空所有参数吗？').then(() => {
          this.saveParams([])
        })
      } else {
        const newParamsList = cloneDeep(this.$refs.TemplateParams.paramsList)
        if (!newParamsList.length) {
          this.$modal.msgError('请添加参数')
          return
        }
        this.saveParams(this.flattenTree(newParamsList))
      }
    },
    // 保存参数
    saveParams(arr) {
      const saveData = {
        id: this.templateInfo.id,
        paramsList: arr
      }
      this.btnLoading = true
      saveTemplateParams(saveData).then(() => {
        this.$message.success('保存成功')
        this.closeDialog()
      }).finally(() => this.btnLoading = false)
    },
    // 展开树结构数据
    flattenTree(tree) {
      let result = [];
      const traverse = function (node) {
        if (node) {
          // 把当前节点加入结果数组
          result.push(node);

          // 如果当前节点有子节点，则递归处理每个子节点
          if (node.children && node.children.length > 0) {
            for (let child of node.children) {
              traverse(child);
            }
          }
        }
      }
      // 遍历树中的每一个根节点
      for (let root of tree) {
        traverse(root);
      }
      return result;
    }
  }
}
</script>

<style scoped>
::v-deep .el-dialog__body {
  padding: 1%;
}
</style>
